' --- Copyright (c) notice DnnConsulting ---
'  Copyright (c) 2013 Dnn Consulting.  www.DnnConsulting.nl. BSD License.
' Author: D.C.Lee
' ------------------------------------------------------------------------
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
' ------------------------------------------------------------------------
' This copyright notice may NOT be removed, obscured or modified without written consent from the author.
' --- End copyright notice --- 

Imports DotNetNuke.Entities.Modules
Imports System.IO
Imports Google.GData.Photos
Imports Google.GData.Client
Imports Google.GData.Extensions
Imports Google.GData.Extensions.Location

Partial Class Gallery
    Inherits DnnC_PicasaAlbumsModuleBase
    Implements IActionable

#Region "Event Handlers"

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            If Not Page.IsPostBack Then

                If Not CType(Settings("DNNC_PGALLERY_USERNAME"), String) = "" Then
                    GetPicasaAblums(Settings("DNNC_PGALLERY_USERNAME"), Settings("DNNC_PGALLERY_PASSWORD"))
                    If Not Request.QueryString("aId") = Nothing Then
                        btnBackToAlbums.Text = Settings("DNNC_PGALLERY_BACKTOALBUMS")

                        SetUpScript()
                        PanelAlbums.Visible = False
                        PanelGallerifficPhotos.Visible = True
                        GetPicasaPhotos(Request.QueryString("aId"), Settings("DNNC_PGALLERY_USERNAME"), Settings("DNNC_PGALLERY_PASSWORD"))
                        PanelPicasaAlbums.Visible = True
                    End If

                Else
                    PanelNofication.Visible = True
                    lblError.Text = Localization.GetString("lblUserNameError", LocalResourceFile)
                End If

            End If

        Catch ex As Exception        'Module failed to load
            lblError.Text = ex.ToString
        End Try
    End Sub

    Private Sub btnBackToAlbums_Click(sender As Object, e As System.EventArgs) Handles btnBackToAlbums.Click
        Response.Redirect(NavigateURL(Me.TabId, "", "mid=" & ModuleId))
    End Sub

    Private Sub ddlAlbums_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ddlAlbums.SelectedIndexChanged
        Response.Redirect(NavigateURL(Me.TabId, "", "mid=" & ModuleId & "&aId=" & ddlAlbums.SelectedValue))
    End Sub

#End Region

#Region "Private methods"

    Private Sub SetUpScript()
        Try
            Dim strI As StringBuilder = New StringBuilder
            strI.AppendLine("<link rel=""stylesheet"" href=""" & ControlPath & "css/basic.css"" type=""text/css"">")
            strI.AppendLine("<script type=""text/javascript"" src=""" & ControlPath & "js/jquery.galleriffic.js""></script>")
            strI.AppendLine("<script type=""text/javascript"" src=""" & ControlPath & "js/jquery.opacityrollover.js""></script>")
            ltlIncludes.Text = strI.ToString

            Dim strS As StringBuilder = New StringBuilder
            strS.AppendLine("<Style type=""text/css"">")
            If Not CType(Settings("DNNC_PGALLERY_GALCSS"), String) Is Nothing Then
                strS.AppendLine(CType(Settings("DNNC_PGALLERY_GALCSS"), String))
            Else
                strS.Append(LoadFile("galcss"))
            End If
            strS.AppendLine("</style>")

            strS.AppendLine("<script type=""text/javascript"">")
            If Not CType(Settings("DNNC_PGALLERY_GALSCRIPT"), String) Is Nothing Then
                strS.AppendLine(CType(Settings("DNNC_PGALLERY_GALSCRIPT"), String))
            Else
                LoadFile("galscript")
            End If
            strS.AppendLine("</script>")

            strS.AppendLine("<Style type=""text/css"">")
            If Not CType(Settings("DNNC_PGALLERY_CATSTYLE"), String) Is Nothing Then
                strS.AppendLine(CType(Settings("DNNC_PGALLERY_CATSTYLE"), String))
            Else
                LoadFile("galcatstyle")
            End If
            strS.AppendLine("</style>")

            ltlScript.Text = strS.ToString

        Catch ex As Exception
            PanelNofication.Visible = True
            lblError.Text = ex.ToString
        End Try
    End Sub

    Private Function LoadFile(fileToLoad As String) As String
        Try
            Dim fStr As StringBuilder = New StringBuilder
            Dim fn As String = String.Empty

            Select Case fileToLoad
                Case "galcss" : fn = Server.MapPath(ControlPath & "files/Galleriffic_style.txt")
                Case "galscript" : fn = Server.MapPath(ControlPath & "files/Galleriffic_script.txt")
                Case "galcatstyle" : fn = Server.MapPath(ControlPath & "files/Category_style.txt")
            End Select

            Dim sr As StreamReader
            sr = File.OpenText(fn)
            While sr.Peek() <> -1
                fStr.AppendLine(sr.ReadLine())
            End While
            sr.Close()

            Return fStr.ToString

        Catch ex As Exception
            PanelNofication.Visible = True
            lblError.Text = ex.ToString
        End Try
    End Function

    Private Sub GetPicasaAblums(userName As String, passWord As String)
        Try

            Dim catStr As StringBuilder = New StringBuilder
            catStr.AppendLine("<style type=""text/css"">")
            catStr.AppendLine(Settings("DNNC_PGALLERY_CATSTYLE"))
            catStr.AppendLine("</style>")
            ltlCatSyle.Text = catStr.ToString

            Dim pService As PicasaService = New PicasaService("freak.roach-sample")
            pService.setUserCredentials(userName, passWord)  ' needed when you need to show albums with private visibility

            Dim qry As AlbumQuery = New AlbumQuery(PicasaQuery.CreatePicasaUri(userName))
            Dim feed As PicasaFeed = pService.Query(qry)

            Dim html As StringBuilder = New StringBuilder
            html.Append("<ul class=""thumbs noscript"">")

            For Each entry As PicasaEntry In feed.Entries
                html.Append("<li>")

                html.Append([String].Format( _
                    "<a href=""{2}""><img src=""{0}"" alt=""{1}"" class=""DnnC_CatImageStyle""/></a>", _
                        entry.Media.Thumbnails(0).Url, entry.Title.Text, NavigateURL( _
                        Me.TabId, "", _
                        "mid=" & ModuleId, _
                        "&aId=" & entry.GetPhotoExtensionValue(Google.GData.Photos.GPhotoNameTable.Id))))
                html.Append("<br/>")

                html.Append([String].Format( _
                    "<a href=""{2}"" class=""DnnC_CatLinkStyle"">{1}</a>", _
                        entry.Media.Thumbnails(0).Url, entry.Title.Text, NavigateURL( _
                        Me.TabId, "", _
                        "mid=" & ModuleId, _
                        "&aId=" & entry.GetPhotoExtensionValue(Google.GData.Photos.GPhotoNameTable.Id))))
                html.Append("<br/>")
                html.Append([String].Format("<span class=""DnnC_CatTextStyle "">{0} images</span>", entry.GetPhotoExtensionValue(Google.GData.Photos.GPhotoNameTable.NumPhotos)))
                html.Append("</li>")
            Next

            html.Append("<ul>")
            divAlbums.InnerHtml = html.ToString()

        Catch ex As Exception
            PanelNofication.Visible = True
            lblError.Text = ex.ToString
        End Try
    End Sub

    Private Sub GetPicasaPhotos(AlbumId As String, userName As String, passWord As String)
        Try

            SetUpAlbumDropDown(userName, passWord)
            Dim pService As PicasaService = New PicasaService("freak.roach-sample")
            pService.setUserCredentials(userName, passWord)  ' needed when you need to show albums with private visibility

            Dim qry As PhotoQuery = New PhotoQuery(PicasaQuery.CreatePicasaUri(userName, AlbumId))
            Dim feed As PicasaFeed = pService.Query(qry)

            Dim html As StringBuilder = New StringBuilder
            html.Append("<ul class=""thumbs noscript"">")

            For Each Entry As PicasaEntry In feed.Entries
                Dim title As String = Entry.Title.Text.Substring(0, Entry.Title.Text.LastIndexOf("."))

                html.Append([String].Format("<li><a class=""thumb"" name=""{0}"" href=""{1}"" title=""{0}""><img src=""{2}"" alt=""{3}""/></a>", title, Entry.Media.Content.Url, Entry.Media.Thumbnails(0).Url, Entry.Summary.Text))
                html.Append([String].Format("<div class=""caption""><div class=""image-title"">{0}</div><div class=""image-desc"">{1}</div></div></li>", title, Entry.Summary.Text))


            Next

            html.Append("</ul>")

            divSlider.InnerHtml = html.ToString()
        Catch ex As Exception
            PanelNofication.Visible = True
            lblError.Text = ex.ToString
        End Try
    End Sub

    Private Sub SetUpAlbumDropDown(userName As String, passWord As String)
        Try
            Dim pService As PicasaService = New PicasaService("freak.roach-sample")
            pService.setUserCredentials(userName, passWord)  ' needed when you need to show albums with private visibility

            Dim qry As AlbumQuery = New AlbumQuery(PicasaQuery.CreatePicasaUri(userName))
            Dim feed As PicasaFeed = pService.Query(qry)

            For Each entry As PicasaEntry In feed.Entries
                ddlAlbums.Items.Add(New ListItem(entry.Title.Text & " (" & entry.GetPhotoExtensionValue(Google.GData.Photos.GPhotoNameTable.NumPhotos) & ")", entry.GetPhotoExtensionValue(Google.GData.Photos.GPhotoNameTable.Id)))
            Next

            ddlAlbums.SelectedValue = Request.QueryString("aId")

        Catch ex As Exception
            PanelNofication.Visible = True
            lblError.Text = ex.ToString
        End Try
    End Sub

#End Region


#Region "Optional Interfaces"

    Public ReadOnly Property ModuleActions() As Entities.Modules.Actions.ModuleActionCollection Implements Entities.Modules.IActionable.ModuleActions
        Get
            Dim Actions As New Entities.Modules.Actions.ModuleActionCollection
            Actions.Add(GetNextActionID, Localization.GetString(Entities.Modules.Actions.ModuleActionType.AddContent, LocalResourceFile), Entities.Modules.Actions.ModuleActionType.AddContent, "", "", EditUrl(), False, DotNetNuke.Security.SecurityAccessLevel.Edit, True, False)
            Return Actions
        End Get
    End Property

#End Region

End Class

